const Router = require('koa-joi-router')
const Joi = Router.Joi
const {convertGlobPaths} = require('node-util')
const apis = ['./src/controller/*.js']
const routes = []

for (const f of convertGlobPaths(apis)) {
  const c = require(f)
  const router = Router()
  const entries = Object.entries(c)
  for (const e of entries) {
    const value = e[1]
    if (e[0] === 'prefix') {
      router.prefix(value)
    } else if (typeof value === 'function') {
      const config = value(Joi)
      if (config?.method && config?.path && config?.handler) {
        router.route(config)
      }
    }
  }

  routes.push(router.middleware())
}

module.exports = routes